package cn.zqh.commodity.utils;

import cn.zqh.bean.bo.*;
import cn.zqh.commodity.client.BrandClient;
import cn.zqh.commodity.client.StoreClient;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import static cn.zqh.bean.contents.ElasticSearchCommodity.MAPPING_COMMODITY;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: zqh
 * @Date: 2023-01-09-11:40
 * @Description: 商品上传es的工具类$
 */
@Configuration
public class EsCommodityUtils {
    private static final String INDEX_LIBRARY = "bs_commodity";

    private static final String AUTOCOMPLETE_FIELD_NAME = "suggestion";

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private StoreClient storeClient;

    @Autowired
    private BrandClient brandClient;

   /**
     * @Author: zqh
     * @Date:
     * @Description: 创建commodity表的es数据库
   */
   public boolean CreateIndex()throws IOException {
       //1创建request对象
       CreateIndexRequest request = new CreateIndexRequest(INDEX_LIBRARY);
       //2准备请求的参数
       request.source(MAPPING_COMMODITY, XContentType.JSON);
       //3发送请求
       client.indices().create(request, RequestOptions.DEFAULT);
       return true;
   }


    /**
     * @Author: zqh
     * @Date:
     * @Description: 删除Commodity表的es数据库
     */
    public boolean DeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(INDEX_LIBRARY);
        client.indices().delete(request, RequestOptions.DEFAULT);
        return true;
    }


    /**
     * @Author: zqh
     * @Date:
     * @Description: 判断es数据库是否存在
     */
    public boolean GetIndex()throws IOException {
        GetIndexRequest request = new GetIndexRequest(INDEX_LIBRARY);
        Boolean expected = client.indices().exists(request, RequestOptions.DEFAULT);
        return expected;
    }

    /**
     * @Author: zqh
     * @Date:
     * @Description: 上传一条数据库到es
     */
    public boolean addOne(Commodity commodity) throws IOException {
        List<String> list = new ArrayList<>() ;
        EsCommodity esCommodity = new EsCommodity();
        String style = commodity.getStyle();
        String[] split = style.split(",");
        if(split.length > 1) {
            for (String s : split) {
                list.add(s);
            }
        }else {
            list.add(style);
        }
        list.add(commodity.getCommodityName());
        System.out.println(commodity.getBrandId()+"342343434");
        //不需要商家，这里不需要了
//        Store store = storeClient.getStoreInformationByStoreId(commodity.getStoreId());
//        list.add(store.getStoreName());
        Brand brand = brandClient.getBrandById(commodity.getBrandId());
        System.out.println(brand);
        list.add(brand.getBrandName());
        esCommodity.setCommodityId(commodity.getCommodityId())
                .setCommodityName(commodity.getCommodityName())
                .setAvatar(commodity.getAvatar())
                .setIntro(commodity.getIntro())
                .setBrandName(brand.getBrandName())
                .setPrice(commodity.getPrice())
                .setNumber(commodity.getNumber())
                .setSalesVolume(commodity.getSalesVolume())
                .setCreateTime(String.valueOf(commodity.getCreateTime()))
                .setUpdateTime(String.valueOf(commodity.getUpdateTime()))
                .setIsDelete(commodity.getIsDelete())
                .setStyleName(style)
                .setSuggestion(list)
                .setStoreName("Moore Makeup Garden");

//        FoodPlus foodPlus = new FoodPlus(food);
        IndexRequest id = new IndexRequest(INDEX_LIBRARY).id(esCommodity.getCommodityId());
        id.source(JSON.toJSONString(esCommodity),XContentType.JSON);
        IndexResponse index = client.index(id, RequestOptions.DEFAULT);
        int successful = index.getShardInfo().getSuccessful();
        return successful == 1 ? true : false;
    }

     /**
       * @Author: zqh
       * @Date:
       * @Description: 上传多条商品数据到es数据库
     */
     public boolean addAll(List<Commodity> commoditys)throws IOException {
         BulkRequest request = new BulkRequest();
         for (Commodity commodity : commoditys) {
             List<String> list = new ArrayList<>() ;

             EsCommodity esCommodity = new EsCommodity();
             String style = commodity.getStyle();
             String[] split = style.split(",");
             for (String s : split) {
                 list.add(s);
             }
             list.add(commodity.getCommodityName());
             //这里不需要了，没有店铺
//             Store store = storeClient.getStoreInformationByStoreId(commodity.getStoreId());
//             list.add(store.getStoreName());
             Brand brand = brandClient.getBrandById(commodity.getBrandId());
             list.add(brand.getBrandName());
             esCommodity.setCommodityId(commodity.getCommodityId())
                     .setCommodityName(commodity.getCommodityName())
                     .setAvatar(commodity.getAvatar())
                     .setIntro(commodity.getIntro())
                     .setBrandName(brand.getBrandName())
                     .setPrice(commodity.getPrice())
                     .setNumber(commodity.getNumber())
                     .setSalesVolume(commodity.getSalesVolume())
                     .setCreateTime(String.valueOf(commodity.getCreateTime()))
                     .setUpdateTime(String.valueOf(commodity.getUpdateTime()))
                     .setIsDelete(commodity.getIsDelete())
                     .setStyleName(style)
                     .setSuggestion(list)
                     .setStoreName("Moore Makeup Garden");
             request.add(new IndexRequest(INDEX_LIBRARY).id(commodity.getCommodityId()).source(JSON.toJSONString(esCommodity),XContentType.JSON));

         }
         client.bulk(request,RequestOptions.DEFAULT);
         return true;
     }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 删除某条数据
    */
    public boolean deleteOne(String id)throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(INDEX_LIBRARY, id);
        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
        int successful = delete.getShardInfo().getSuccessful();
        return successful == 1 ? true : true;
    }

    /**
     * @Author: zqh
     * @Date:
     * @Description: 修改某个
     */
    public boolean updateOne(Commodity commodity) throws IOException {
        IndexRequest id = new IndexRequest(INDEX_LIBRARY).id(commodity.getCommodityId());
        id.source(JSON.toJSONString(commodity),XContentType.JSON);
        IndexResponse index = client.index(id, RequestOptions.DEFAULT);
        int successful = index.getShardInfo().getSuccessful();
        return successful == 1 ? true : false;
    }

    /**
     * @Author: zqh
     * @Date:
     * @Description: 自动补全，用于别人输入查询时自动补全
     */
    public List<String> getAutocompletionList(String content) throws IOException {
        SearchRequest request = new SearchRequest(INDEX_LIBRARY);
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(content)
                        .skipDuplicates(true)
                        .size(10)
        ));
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        CompletionSuggestion getAutocompletionList = search.getSuggest().getSuggestion("suggestions");
        List<String> strings = new ArrayList<>();
        List<CompletionSuggestion.Entry.Option> options1 = getAutocompletionList.getOptions();
        for (CompletionSuggestion.Entry.Option option : options1) {
            String s = option.getText().toString();
            strings.add(s);
        }
        return strings;
    }



    /**
      * @Author: zqh
      * @Date:
      * @Description: 多条件复合查询
     * @return
    */
    public HashMap<String, Object> multiConditionalCompoundQuery(SearchBean searchBean)throws IOException{
        HashMap<String, Object> hashMap = new HashMap<>();
        SearchRequest request = new SearchRequest(INDEX_LIBRARY);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = searchBean.getKey();
        //关键字搜索
        if (key == null || "".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        //条件过滤
        if (searchBean.getBrandName() != null && !"".equals(searchBean.getBrandName())){
            boolQuery.filter(QueryBuilders.matchQuery("brandName",searchBean.getBrandName()));
        }

        //价钱范围
        if (searchBean.getMinPrice() != null && searchBean.getMaxPrice() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(searchBean.getMinPrice()).lte(searchBean.getMaxPrice()));
        }
        int page = searchBean.getPage();
        int size = searchBean.getSize();
        //分页
        request.source().query(boolQuery).from((page-1)*size).size(size);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        List<EsCommodity> commoditys = new ArrayList<>();
        SearchHits hits1 = response.getHits();
        long totalHits = hits1.getTotalHits().value;
        System.out.println(totalHits);
        SearchHit[] hits = hits1.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            EsCommodity commodity = JSON.parseObject(sourceAsString, EsCommodity.class);
            commoditys.add(commodity);
        }
        List<EsCommodity> commodities = handleResponse(response);
        hashMap.put("escommoditys",commodities);
        hashMap.put("title",totalHits);

        return hashMap;
    }



    /**
      * @Author: zqh
      * @Date:
      * @Description: 根据id查询商品
    */
    public EsCommodity getEsCommodityById(String id)throws IOException{
        SearchRequest searchRequest = new SearchRequest(INDEX_LIBRARY);
        searchRequest.source().query(QueryBuilders.matchQuery("commodityId",id));
//        searchRequest.source().from(page).size(size);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//        SearchRequest request = new SearchRequest(INDEX_LIBRARY);
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        boolQuery.must(QueryBuilders.matchQuery("commodityId",id));
//        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        if (response != null){
        List<EsCommodity> esCommodities = handleResponse(response);
        if (esCommodities.size() > 0){
            return esCommodities.get(0);
        }else{
            return null;
        }
        }
        else {
            return null;
        }
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 处理返回结果
    */
    private List<EsCommodity> handleResponse(SearchResponse search) {
        List<EsCommodity> commoditys = new ArrayList<>();
        SearchHits hits1 = search.getHits();
        SearchHit[] hits = hits1.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            EsCommodity commodity = JSON.parseObject(sourceAsString, EsCommodity.class);
            commoditys.add(commodity);
//            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //高亮
//            if (highlightFields != null) {
//                HighlightField shop_name = highlightFields.get("shopName");
//                if (shop_name != null) {
//                    String string = shop_name.getFragments()[0].string();
//                    shop.setShopName(string);
//                }
//            }

//            sojShops.add(SojShop.getSojShopByEsShop(shop));
        }
        return commoditys;
    }

}
